package com.cy.pj.goods.controller;

import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/goods")//定义url中的共性部分
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @GetMapping("/doFindGoods")
    public String doFindGoods(Model model){
        List<Goods> list = goodsService.findGoods();
        model.addAttribute("list", list);
        return "goods";//viewname
    }
    @ResponseBody
    @GetMapping("doFindJsonGoods")
    public JsonResult doFindJsonGoods(String name){
        List<Goods> list = goodsService.select(name);
        return  new JsonResult(list);
    }
    @RequestMapping("/doDeleteById/{id}")
    public String doDeleteById(@PathVariable Integer id){
        goodsService.deleteById(id);
        return "redirect:/goods/doFindGoods";
    }
    @RequestMapping("/doDeleteById")
    public String doDeleteById(Integer id, Model model){
        goodsService.deleteById(id);
        List<Goods> list = goodsService.findGoods();
        model.addAttribute("list", list);
            return "goods";
    }
    @RequestMapping("/doSaveGoods")
    public String doSaveGoods(Goods entity) {
        goodsService.saveGoods(entity);
        return "redirect:/goods/doFindGoods";
    }
    @RequestMapping("/doSaveGoodss")
    public String doSaveGoods(Goods goods,Model model) {
        goodsService.saveGoods(goods);
        List<Goods> list = goodsService.findGoods();
        model.addAttribute("list", list);
        return "redirect:/goods/doFindGoods";
    }
    /*
    响应一个商品添加页面
     */
    @RequestMapping("/doGoodsAddUI")
    public String doGoodsAddUI() {

        return "goods-add";
    }
    @GetMapping("/doFindById/{id}")
    public String doFindById(@PathVariable Integer id,Model model){
        Goods goods =  goodsService.findById(id);
        model.addAttribute("goods", goods);
        return  "goods-update";
    }
    @PostMapping("/doUpdateGoods")
    public String doUpdateGoods(Goods goods,Model model){
       goodsService.updateGoods(goods);
        List<Goods> list = goodsService.findGoods();
        model.addAttribute("list", list);
        return "goods";
    }
    @RequestMapping("/doSelecteGoods")
    public String doSelecteGoods(String name,Model model){
        System.out.println("GoodsController.doSelecteGoods"+name);
        List<Goods> list = goodsService.select(name);
        for (Goods g:list) {
            System.out.println(g);
        }
        model.addAttribute("list", list);
        return "goods";
    }

}



